package netty.demo.nio.selector.write;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author Zed
 * @description
 * @date 2022/10/24 20:19
 */
public class WriteServer {
    public static void main(String[] args) {
        try {
            ServerSocketChannel socketChannel = ServerSocketChannel.open();
            socketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
            socketChannel.bind(new InetSocketAddress(8080));
            while (true) {
                selector.select();
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    keyIterator.remove();
                    if (key.isAcceptable()) {
                        SocketChannel channel = socketChannel.accept();
                        channel.configureBlocking(false);

                        //1.向客户端发送大量数据
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < 30000000; i++) {
                            stringBuilder.append("a");
                        }
                        ByteBuffer byteBuffer = Charset.defaultCharset().encode(stringBuilder.toString());
                        //2.判断是否有剩余内容
                        while (byteBuffer.hasRemaining()) {
                            //3.返回值,实际写入的字节数
                            int write = channel.write(byteBuffer);
                            System.out.println(write);
                        }
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
